package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrTime类
 * 实现时间数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrTime implements AxdrType {
    private byte[] value = new byte[3]; // 3字节时间数据
    private byte[] dataCode = null;

    public AxdrTime() {
    }

    public AxdrTime(byte[] value) {
        if (value.length != 3) {
            throw new IllegalArgumentException("Time value must be 3 bytes");
        }
        System.arraycopy(value, 0, this.value, 0, 3);
    }

    public byte[] getValue() {
        return value;
    }

    public void setValue(byte[] value) {
        if (value.length != 3) {
            throw new IllegalArgumentException("Time value must be 3 bytes");
        }
        System.arraycopy(value, 0, this.value, 0, 3);
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // 解码3个字节的时间数据
        this.value[0] = (byte) input.read();
        this.value[1] = (byte) input.read();
        this.value[2] = (byte) input.read();
        return 3;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        // 编码3个字节的时间数据
        try {
            output.write(this.value[0]);
            output.write(this.value[1]);
            output.write(this.value[2]);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return 3;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        return String.format("Time[%02X%02X%02X]",
                this.value[0] & 0xFF,
                this.value[1] & 0xFF,
                this.value[2] & 0xFF);
    }
}